import { mapState } from 'vuex'
export default {
  data () {
    return {
      ysqxxLayersLoaded: false,
      deepLayerId: 'ysqxx_CITY_deep',
      shallowLayerId: 'ysqxx_CITY_shallow'
    }
  },
  computed: {
    ...mapState('map', ['initLayerZIndexMap']),
    ...mapState('ysqxx', ['mapStationQueryParam'])
  },
  methods: {
    async createLayers () {
      // 恢复到全貌
      setTimeout(() => {
        this.$mapManager.invoke('setZoom', 'quanmao')
      }, 200)
      const layers = this.legends.map(item => ({
        bklayerGroupId: item.groupName,
        bklayerId: item.layerId,
        bklayerName: item.name,
        bklayerType: 'vectorlayer_empty',
        bklayerSn: this.initLayerZIndexMap[item.layerId],
        clusterSn: this.initLayerZIndexMap[item.layerId + '_cluster'],
        visible: item.visible ?? true,
        needCluster: item.needCluster ?? false,
        hasText: item.hasText ?? false,
        textKey: item.textKey,
        isClick: item.isClick ?? false,
        isHover: item.isHover ?? false,
        declutter: true
      }))
      await this.$mapManager.invoke('addLayers', layers)
      this.ysqxxLayersLoaded = true
    },
    async getGeoByParams (methodParams) {
      const { rows } = await this.$request.singleTableOperation({
        url: '/grid/getTableData',
        metaSet: 'YSQJC_ST_STBPRP_B',
        methodCode: 'STCD_getList',
        methodParams: methodParams || this.mapStationQueryParam
      })
      return rows
    },
    async renderMapPoints (rows, layerId, imgId) {
      const layer = await this.$mapManager.invokeUtils('getLayer', layerId)
      const features = []
      for (const row of rows) {
        const point = this.$mapManager.getMapComponent().map1.bkol.getPoint(row.LGTD, row.LTTD)
        const feature = new window.ol.Feature(point)
        // const imgId = layerId.endsWith('_cluster') ? layerId.split('_')[0] : layerId
        const style = this.getStyleByLayerId(imgId, layerId, row)
        feature.setProperties(Object.assign({ img: require(`@/assets/images/ysqxx/map/${imgId}.png`) }, row, { layerId }))
        feature.setStyle(style)
        feature.set('selectStyle', (feature) => this.selectStyle(feature, imgId, row), true)
        features.push(feature)
      }
      layer.getSource().addFeatures(features)
      if (layer.get('hasCluster')) {
        await this.$mapManager.invoke('renderClusterLayer', layerId, features)
      }
    },
    getStyleByLayerId (imgId, layerId, row, isSelect = false) {
      const iconOption = new window.ol.style.Icon({
        offset: [0, 0],
        opacity: 1,
        scale: 1,
        src: require(`@/assets/images/ysqxx/map/${imgId}.png`)
      })
      const text = new window.ol.style.Text({
        font: 'bold 0.7rem YouSheBiaoTiHei sans-serif',
        text: row.STNM || '',
        fill: new window.ol.style.Fill({
          color: isSelect ? '#34d7fa' : '#ffffff'
        }),
        backgroundFill: new window.ol.style.Fill({
          color: 'rgba(8, 49, 102, 1)'
        }),
        backgroundStroke: new window.ol.style.Stroke({
          color: '#34d7fa',
          width: 1
        }),
        offsetY: 35,
        textAlign: 'center',
        padding: [3, 4, 2, 4]
      })
      const option = { image: iconOption, text: text }
      return new window.ol.style.Style(option)
    },
    async clearLayerById (layerId) {
      const layer = await this.$mapManager.invokeUtils('getLayer', layerId)
      if (layer) {
        layer.getSource().clear()
        if (layer.get('hasCluster')) {
          const clusterLayer = await this.$mapManager.invokeUtils('getLayer', layerId + '_cluster')
          // 聚合图层需要get两次
          if (clusterLayer) {
            clusterLayer.getSource().getSource().clear()
          }
        }
      } else {
        console.error('图层' + layerId + '不存在')
      }
    },
    clearAllLayers () {
      this.$mapManager.invoke('clearSelectStyle')
      this.legends.forEach(item => {
        this.clearLayerById(item.layerId)
      })
    },
    // 确保点击后不位移
    selectStyle (feature, imgId, row) {
      const layerId = feature.getProperties().layerId
      const style = this.getStyleByLayerId(imgId, layerId, row, true)
      feature.setStyle(style)
    },
    // 根据行政区加点
    async createLayerByCity (city, rows, visible) {
      const deepLayerId = this.deepLayerId
      const shallowLayerId = this.shallowLayerId
      if (!visible) {
        await this.$mapManager.invoke('setLayerVisible', `${deepLayerId},${shallowLayerId}`, false)
        const allLayerIds = this.$mapManager.getMapComponent().map1.layerManager.getAllLayer()
        const otherLayerIds = allLayerIds.filter((id) => {
          return id.startsWith('ysqxx_') && !id.startsWith('ysqxx_CITY')
        })
        await this.$mapManager.invoke('setLayerVisible', otherLayerIds.join(','), true)
      } else {
        const deepLayer = {
          bklayerGroupId: 'CITY',
          bklayerId: deepLayerId,
          bklayerName: '行政区划',
          bklayerType: 'vectorlayer_empty',
          bklayerSn: this.initLayerZIndexMap[deepLayerId],
          clusterSn: this.initLayerZIndexMap[deepLayerId + '_cluster'],
          visible: true,
          needCluster: true,
          isClick: true,
          declutter: false // 不可遮挡
        }
        const shallowLayer = {
          bklayerGroupId: 'CITY',
          bklayerId: shallowLayerId,
          bklayerName: '行政区划',
          bklayerType: 'vectorlayer_empty',
          bklayerSn: this.initLayerZIndexMap[shallowLayerId],
          clusterSn: this.initLayerZIndexMap[shallowLayerId + '_cluster'],
          visible: true,
          needCluster: true,
          isClick: true,
          declutter: false // 不可遮挡
        }
        await this.$mapManager.invoke('addLayers', [deepLayer, shallowLayer])
        await this.clearLayerById(deepLayerId)
        await this.clearLayerById(shallowLayerId)
        // 加点
        await this.renderMapPoints(rows.filter(item => item.DASL === '2'), deepLayerId, 'ysqxx_city_deep')
        await this.renderMapPoints(rows.filter(item => item.DASL === '1'), shallowLayerId, 'ysqxx_city_shallow')
        // 其他图层控制
        const allLayerIds = this.$mapManager.getMapComponent().map1.layerManager.getAllLayer()
        const otherLayerIds = allLayerIds.filter((id) => {
          return id.startsWith('ysqxx_') && (!id.startsWith('ysqxx_CITY'))
        })
        await this.$mapManager.invoke('setLayerVisible', otherLayerIds.join(','), false)
      }
    }
  }
}
